package com.ruoyi.web.controller.net;

import com.ruoyi.net.domain.ElementPortMtnPhy;
import com.ruoyi.net.domain.ElementPortTrunk;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementProtectGroup;
import com.ruoyi.net.service.IElementProtectGroupService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 网元-保护配置-细粒度保护组Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-保护配置-细粒度保护组")
@RestController
@RequestMapping("/element/protect/group")
public class ElementProtectGroupController extends BaseController {
    @Autowired
    private IElementProtectGroupService elementProtectGroupService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-保护配置-细粒度保护组列表
     */
    @ApiOperation(value = "查询网元-保护配置-细粒度保护组列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:group:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementProtectGroup elementProtectGroup) {
        startPage();
        List<ElementProtectGroup> list = elementProtectGroupService.selectElementProtectGroupList(elementProtectGroup);
        return getDataTable(list);
    }

    /**
     * 导出网元-保护配置-细粒度保护组列表
     */
    @ApiOperation(value = "导出网元-保护配置-细粒度保护组列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:group:export')")
    @Log(title = "网元-保护配置-细粒度保护组", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementProtectGroup elementProtectGroup) {
        List<ElementProtectGroup> list = elementProtectGroupService.selectElementProtectGroupList(elementProtectGroup);
        ExcelUtil<ElementProtectGroup> util = new ExcelUtil<ElementProtectGroup>(ElementProtectGroup.class);
        util.exportExcel(response, list, "网元-保护配置-细粒度保护组数据");
    }

    /**
     * 获取网元-保护配置-细粒度保护组详细信息
     */
    @ApiOperation(value = "获取网元-保护配置-细粒度保护组详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:group:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementProtectGroupService.selectElementProtectGroupById(id));
    }

    /**
     * 新增网元-保护配置-细粒度保护组
     */
    @ApiOperation(value = "新增网元-保护配置-细粒度保护组", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:group:add')")
    @Log(title = "网元-保护配置-细粒度保护组", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementProtectGroup elementProtectGroup) {
        return toAjax(elementProtectGroupService.insertElementProtectGroup(elementProtectGroup));
    }

    /**
     * 修改网元-保护配置-细粒度保护组
     */
    @ApiOperation(value = "修改网元-保护配置-细粒度保护组", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:group:edit')")
    @Log(title = "网元-保护配置-细粒度保护组", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementProtectGroup elementProtectGroup) {
        return toAjax(elementProtectGroupService.updateElementProtectGroup(elementProtectGroup));
    }

    /**
     * 删除网元-保护配置-细粒度保护组
     */
    @ApiOperation(value = "删除网元-保护配置-细粒度保护组", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:group:remove')")
    @Log(title = "网元-保护配置-细粒度保护组", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementProtectGroupService.deleteElementProtectGroupByIds(ids));
    }

    /**
     * 激活设备
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementProtectGroup entity = elementProtectGroupService.selectElementProtectGroupById(id);
        entity.setStatus("1");
        if (sendXml(entity)){
            return toAjax(elementProtectGroupService.updateElementProtectGroup(entity));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementProtectGroup entity =  elementProtectGroupService.selectElementProtectGroupById(id);
        entity.setStatus("0");
        if (sendXml(entity)){
            return toAjax(elementProtectGroupService.updateElementProtectGroup(entity));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementProtectGroup entity) {
        boolean isSend = true;
        // TODO: 2024/12/8 设备联调
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());
            String operation = "create";
            if ("0".equals(entity.getStatus())) {
                operation = "remove";
            }
            /*<fgboard-grp xmlns="http://fiberhome.com/fhnw/yang/protectgroup/fos-fgboardgroup">
                    <fg-board-group-cfgs>
                    <fg-board-group-cfg>
                    <fg-board-group-index>1</fg-board-group-index>
                    <member-slot-list>
                    <slot-num>0/26/0</slot-num>
                    </member-slot-list>
                    </fg-board-group-cfg>
                    </fg-board-group-cfgs>
                    </fgboard-grp>*/
            StringBuilder xml = new StringBuilder();
            xml.append("<fgboard-grp xmlns=\"http://fiberhome.com/fhnw/yang/protectgroup/fos-fgboardgroup\">" +
                    "    <fg-board-group-cfgs>" +
                    "    <fg-board-group-cfg nc:operation=\"" + operation + "\">" +
                    "        <fg-board-group-index>" + entity.getGroupId() + "</fg-board-group-index>" +
                    "        <member-slot-list>" +
                    "          <slot-num>" + entity.getBusId() + "</slot-num>" + // 0/1/0
                    "        </member-slot-list>" +
                    "      </fg-board-group-cfg>" +
                    "    </fg-board-group-cfgs>" +
                    "  </fgboard-grp>");
            logger.info("保护配置-细粒度保护组激活xml:" + xml.toString());
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }
}